package com.edu.hre.struts.action.survey;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.entity.SurveySummaryBean;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.pojo.HreUserRoleScreen;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.survey.SurveySummaryDetailForm;
import com.fastsearch.esp.search.query.Query;

public class SurveySummaryDetailAction extends DispatchAction {
	
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	
	public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		HreUserRoleScreen userRoleScreen = (HreUserRoleScreen) request.getSession().getAttribute(RequestUtils.Attribute.HreUserRoleScreen);
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveySummaryDetailForm beanForm = (SurveySummaryDetailForm) form;
		
		int id = Integer.parseInt(request.getParameter("id"));
		HreSurveyTopic topic = baseService.getPojo(id, HreSurveyTopic.class);
		HreUser userCreated = baseService.getPojo(topic.getUserCreated(), HreUser.class);
		HreSubunit subunit = baseService.getPojo(topic.getSubunitId(), HreSubunit.class);
		
		beanForm.setId(topic.getId());
		beanForm.setStartDate(topic.getStartDate());
		beanForm.setEndDate(topic.getEndDate());
		beanForm.setTopic(topic.getName());
		beanForm.setSubunit(subunit.getName());
		beanForm.setLastModifiedUser(userCreated.getUserName());
		
		if(topic.getShowToAll() == false && topic.getUserCreated() != user.getId()){
			response.getWriter().write("Invalid time to edit this survey!");
			return null;
		}
		String html = "";
		int checkId = -1;
		ArrayList<SurveySummaryBean> listBean = getListObjs(topic.getId());
		int totalTakenUser = getTotalTakenUser(topic.getId());
		
		request.setAttribute("totalAnswer", listBean.size());
		request.setAttribute("totalTakenUser", totalTakenUser);
		int count = 1;
		for(int i = 0; listBean != null && i < listBean.size(); i ++){
			SurveySummaryBean bean = listBean.get(i);
			if(checkId != bean.getQuestionId()){
				html += "</table></div>";
				html += "<div><hr/>";
				html += "<center><h3>Question " + (count ++) + "</h3></center>";
				html += "<h4>" + bean.getQuestionText() + "</h4>";
				html += "<table width='100%'>";
				checkId = bean.getQuestionId();
			}
			html += "<tr><td width='57%'>";
			html += bean.getAnswerLabel() + ".";
			String answerText = bean.getAnswerText();
			if(bean.getAnswerType() == 2 && bean.getTotalChecked() != 0){
				String hrefContent = "javascript:openPopup(``surveyFreeTextList.do?act=view&id="
						+ bean.getAnswerId() + "``, ``Answer List``,``850px``,``580px``)";   
				answerText = "<a href='" + hrefContent + "' " +
						"style='color:blue;'>" + bean.getAnswerText() + "</a>";
				CommonUtils.println(answerText);
			}
			if(bean.getQuestionType() == 1){
				html += "<input disabled='true' type='checkbox' name='name'>" +  answerText + "</input>";
			} else {
				html += "<input disabled='true' type='radio' name='name'>" +  answerText + "</input>";
			}
			if(bean.getAnswerType() == 2){
				html += "<br/><a style='padding-left:20px;'></a>" +
						"<input disabled='true' type='text' name='name' " +
						"style='background-color:#F6F4F1;' value='.....'>" +
						"</input><br/>";
			}
			html += "</td>";
			String divId = "div" + i;
			html += "<td>";
			html += "<a style='float: left'>" + bean.getAnswerLabel() + ".&nbsp;</a>";
			html += "<div id='" + divId + "' ></div></td>";
			request.setAttribute(divId, bean.getTotalChecked());
			html += "</tr>";
		}
		html += "</table></div>";
		html = html.replace("'", "\"");
		html = html.replace("``", "'");
		html = html.replaceFirst("</table>", "");
		html = html.replaceFirst("</div>", "");
		
		beanForm.setHtml(html);
		return mapping.findForward("surveySummaryDetail");
	}
	
	private int getTotalTakenUser(Integer id) {
		String sql = "select count(*) from (SELECT t.id, a.user_id " +
				"FROM hre_survey_emp_answer a join hre_survey_topic t " +
				"on a.topic_id = t.id group by t.id, a.user_id) tmp where tmp.id = " + id;
		
		Object obj =  baseService.listArrayObject(sql, 0, 0).get(0)[1];
		return (Integer) getValue(obj);
 	}

	private ArrayList<SurveySummaryBean> getListObjs(int topicId){
		String sql = 
			"select sum(tmp.ea_id) as total_checked, tmp.q_id , tmp.q_text, tmp.q_type, tmp.qa_id, " + 
			"    tmp.qa_label, tmp.qa_text, tmp.qa_type " + 
			"from " + 
			"(  " + 
			"    select q.id q_id, q.text q_text, q.type q_type, qa.id qa_id, qa.label " +  
			"        qa_label, qa.text qa_text, qa.type qa_type,  " + 
			"        (CASE WHEN ea.id is not null then 1 else 0 end) ea_id " +  
			"    from hre_survey_question q   " + 
			"    join hre_survey_question_answer qa " +  
			"    on q.id = qa.question_id " +  
			"     " + 
			"    left outer join hre_survey_emp_answer ea " +  
			"    on qa.id = ea.answer  " + 
			"    where q.topic_id = @id  " + 
			"    order by q.rank, qa.label " + 
			") as tmp  " + 
			"group by tmp.q_id, tmp.q_text, tmp.q_type, tmp.qa_id, tmp.qa_label, " + 
			"    tmp.qa_text, tmp.qa_type "; 
		sql = sql.replace("@id", topicId + "");
		List <Object[]> listObjs = baseService.listArrayObject(sql, 0, 0);
		CommonUtils.println(listObjs.size() + "");
		ArrayList<SurveySummaryBean> listBeans = new ArrayList<SurveySummaryBean>();
		for(int i = 0; listObjs != null && i < listObjs.size(); i ++){
			Object[] obj = listObjs.get(i);
			int totalChecked = (Integer) getValue(obj[1]);
			int questionId = (Integer) getValue(obj[2]);
			String questionText = (String) getValue(obj[3]);
			int questionType = (Integer) getValue(obj[4]);
			int answerId = (Integer) getValue(obj[5]);
			String answerLabel = (String) getValue(obj[6]);
			String answerText = (String) getValue(obj[7]);
			int answerType = (Integer) getValue(obj[8]);
			SurveySummaryBean bean = new SurveySummaryBean(totalChecked, questionId,
					questionText, questionType, answerId, answerLabel, answerText, answerType);
			listBeans.add(bean);
		}
		return listBeans;
	}
	
	private Object getValue(Object o){
		if(o == null){
			return o;
		}
		if(o instanceof Integer){
			return (Integer) o;
		}
		if(o instanceof BigInteger){
			return ((BigInteger) o).intValue();
		}
		if(o instanceof BigDecimal){
			return ((BigDecimal) o).intValue();
		}
		return o;
	}
}
